<template>
  <div class="doctor-detail-container">
    <van-nav-bar
      title="医生详情"
      left-arrow
      @click-left="router.back()"
    />

    <!-- 医生基本信息 -->
    <div class="doctor-header">
      <div class="avatar-section">
        <van-image
          round
          width="80"
          height="80"
          :src="doctor?.avatar"
        />
      </div>
      <div class="info-section">
        <div class="name-title">
          <span class="name">{{ doctor?.name }}</span>
          <van-tag type="primary" class="ml-2">{{ doctor?.title }}</van-tag>
        </div>
        <div class="department text-gray-500">
          {{ doctor?.departmentName }}
        </div>
        <div class="statistics">
          <span>接诊量：{{ doctor?.patientCount }}人</span>
          <span class="mx-2">|</span>
          <span>好评率：{{ doctor?.rating }}%</span>
        </div>
      </div>
    </div>

    <!-- 快速操作按钮 -->
    <div class="action-buttons">
      <van-button 
        type="primary" 
        block 
        @click="handleAppointment"
        class="mb-2"
      >
        立即预约
      </van-button>
      <van-button 
        plain 
        type="primary" 
        block
        icon="chat-o"
        @click="handleInquiry"
      >
        在线问诊
      </van-button>
    </div>

    <!-- 医生详细信息 -->
    <van-tabs v-model="activeTab" sticky animated swipeable>
      <!-- 基本信息 -->
      <van-tab title="简介">
        <div class="tab-content">
          <!-- 专业特长 -->
          <div class="info-section-block">
            <div class="section-title">专业特长</div>
            <div class="content-text">{{ doctor?.specialty }}</div>
          </div>

          <!-- 个人简介 -->
          <div class="info-section-block">
            <div class="section-title">个人简介</div>
            <div class="content-text">{{ doctor?.introduction }}</div>
          </div>

          <!-- 教育背景 -->
          <div class="info-section-block" v-if="doctor?.education?.length">
            <div class="section-title">教育背景</div>
            <van-cell-group inset>
              <van-cell 
                v-for="(edu, index) in doctor?.education" 
                :key="index"
                :title="edu.school"
                :label="edu.degree"
                :value="edu.year"
              />
            </van-cell-group>
          </div>

          <!-- 荣誉奖项 -->
          <div class="info-section-block" v-if="doctor?.awards?.length">
            <div class="section-title">荣誉奖项</div>
            <van-cell-group inset>
              <van-cell 
                v-for="(award, index) in doctor?.awards" 
                :key="index"
                :title="award.name"
                :label="award.description"
                :value="award.year"
              />
            </van-cell-group>
          </div>
        </div>
      </van-tab>

      <!-- 出诊时间 -->
      <van-tab title="出诊时间">
        <div class="tab-content">
          <van-calendar
            :show-title="false"
            :min-date="minDate"
            :max-date="maxDate"
            :formatter="calendarFormatter"
            @select="onDateSelect"
          />
          
          <!-- 选中日期的时间段 -->
          <div v-if="selectedDate" class="time-slots">
            <div class="section-title">可预约时间段</div>
            <van-cell-group inset>
              <van-cell
                v-for="slot in timeSlots"
                :key="slot.id"
                :title="slot.time"
                :label="`剩余号源：${slot.remaining}`"
                :disabled="!slot.remaining"
              >
                <template #right-icon>
                  <van-button 
                    size="small" 
                    type="primary"
                    :disabled="!slot.remaining"
                    @click="handleTimeSelect(slot)"
                  >
                    预约
                  </van-button>
                </template>
              </van-cell>
            </van-cell-group>
          </div>
        </div>
      </van-tab>

      <!-- 评价 -->
      <van-tab title="患者评价">
        <div class="tab-content">
          <!-- 评分统计 -->
          <div class="rating-stats">
            <div class="overall-rating">
              <div class="rating-number">{{ doctor?.rating }}</div>
              <van-rate :value="doctor?.rating / 20" readonly allow-half />
              <div class="rating-count">共 {{ doctor?.reviewCount }} 条评价</div>
            </div>
            <div class="rating-tags">
              <van-tag 
                v-for="tag in doctor?.reviewTags" 
                :key="tag.name"
                type="primary"
                plain
                class="mr-2 mb-2"
              >
                {{ tag.name }} {{ tag.count }}
              </van-tag>
            </div>
          </div>

          <!-- 评价列表 -->
          <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <div v-for="review in reviews" :key="review.id" class="review-item">
              <div class="review-header">
                <van-image
                  round
                  width="40"
                  height="40"
                  :src="review.avatar"
                />
                <div class="review-user">
                  <div class="username">{{ maskName(review.username) }}</div>
                  <div class="review-time">{{ formatDate(review.createTime) }}</div>
                </div>
                <van-rate :value="review.rating" readonly size="12" />
              </div>
              <div class="review-content">{{ review.content }}</div>
              <div v-if="review.reply" class="review-reply">
                <span class="text-primary">医生回复：</span>{{ review.reply }}
              </div>
            </div>
          </van-list>
        </div>
      </van-tab>
    </van-tabs>

    <!-- 预约确认弹窗 -->
    <van-dialog
      v-model="showConfirm"
      title="预约确认"
      show-cancel-button
      @confirm="confirmAppointment"
    >
      <div class="p-4">
        <div class="confirm-item">
          <span class="label">就诊医生：</span>
          <span>{{ doctor?.name }}</span>
        </div>
        <div class="confirm-item">
          <span class="label">就诊科室：</span>
          <span>{{ doctor?.departmentName }}</span>
        </div>
        <div class="confirm-item">
          <span class="label">就诊时间：</span>
          <span>{{ formatDateTime(selectedSlot?.date, selectedSlot?.time) }}</span>
        </div>
        <div class="confirm-item">
          <span class="label">挂号费用：</span>
          <span class="text-primary">￥{{ doctor?.fee }}</span>
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import { getDoctorDetail, getDoctorSchedule, getDoctorReviews } from '../api'

const router = useRouter()
const route = useRoute()
const doctor = ref(null)
const activeTab = ref(0)
const loading = ref(false)
const finished = ref(false)
const currentPage = ref(1)
const pageSize = 10
const reviews = ref([])

// 出诊时间相关
const minDate = new Date()
const maxDate = new Date()
maxDate.setDate(maxDate.getDate() + 14) // 可预约未来14天
const selectedDate = ref(null)
const timeSlots = ref([])
const selectedSlot = ref(null)
const showConfirm = ref(false)

// 加载医生详情
const loadDoctorDetail = async () => {
  try {
    const res = await getDoctorDetail(route.params.id)
    doctor.value = res
  } catch (error) {
    console.error('获取医生详情失败：', error)
    showToast('获取医生详情失败')
  }
}

// 加载出诊时间
const loadSchedule = async (date) => {
  try {
    const res = await getDoctorSchedule({
      doctorId: route.params.id,
      date: formatDate(date)
    })
    timeSlots.value = res
  } catch (error) {
    console.error('获取出诊时间失败：', error)
    showToast('获取出诊时间失败')
  }
}

// 加载评价列表
const loadReviews = async () => {
  try {
    const res = await getDoctorReviews({
      doctorId: route.params.id,
      page: currentPage.value,
      size: pageSize
    })
    
    reviews.value.push(...res.content)
    loading.value = false
    
    if (res.content.length < pageSize) {
      finished.value = true
    } else {
      currentPage.value += 1
    }
  } catch (error) {
    console.error('获取评价列表失败：', error)
    showToast('获取评价列表失败')
    loading.value = false
  }
}

// 处理加载更多评价
const onLoad = () => {
  loadReviews()
}

// 处理日期选择
const onDateSelect = (date) => {
  selectedDate.value = date
  loadSchedule(date)
}

// 处理时间段选择
const handleTimeSelect = (slot) => {
  selectedSlot.value = {
    ...slot,
    date: selectedDate.value
  }
  showConfirm.value = true
}

// 确认预约
const confirmAppointment = () => {
  router.push({
    path: '/registration',
    query: {
      doctorId: doctor.value.id,
      departmentId: doctor.value.departmentId,
      date: formatDate(selectedSlot.value.date),
      time: selectedSlot.value.time
    }
  })
}

// 快速预约
const handleAppointment = () => {
  activeTab.value = 1 // 切换到出诊时间标签
}

// 在线问诊
const handleInquiry = () => {
  // TODO: 实现在线问诊功能
  showToast('在线问诊功能开发中')
}

// 日历格式化
const calendarFormatter = (day) => {
  // TODO: 根据医生排班信息处理可预约日期
  return day
}

// 工具函数
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const formatDateTime = (date, time) => {
  if (!date || !time) return ''
  return `${formatDate(date)} ${time}`
}

const maskName = (name) => {
  if (!name) return ''
  return name.length > 2 ? 
    name.charAt(0) + '*'.repeat(name.length - 2) + name.charAt(name.length - 1) :
    name.charAt(0) + '*'
}

onMounted(() => {
  loadDoctorDetail()
})
</script>

<style scoped>
.doctor-detail-container {
  min-height: 100vh;
  background-color: var(--background-color);
}

.doctor-header {
  background-color: #fff;
  padding: 20px;
  display: flex;
  align-items: center;
}

.avatar-section {
  margin-right: 16px;
}

.info-section {
  flex: 1;
}

.name-title {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.name {
  font-size: 18px;
  font-weight: bold;
}

.department {
  margin-bottom: 8px;
}

.statistics {
  font-size: 14px;
  color: var(--van-text-color-2);
}

.action-buttons {
  padding: 16px;
  background-color: #fff;
}

.tab-content {
  padding: 16px;
  background-color: #fff;
}

.info-section-block {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 12px;
  color: var(--van-text-color);
}

.content-text {
  font-size: 14px;
  line-height: 1.6;
  color: var(--van-text-color);
}

.time-slots {
  margin-top: 20px;
}

.rating-stats {
  text-align: center;
  padding: 20px 0;
}

.overall-rating {
  margin-bottom: 16px;
}

.rating-number {
  font-size: 36px;
  font-weight: bold;
  color: var(--van-primary-color);
}

.rating-count {
  font-size: 14px;
  color: var(--van-text-color-2);
  margin-top: 8px;
}

.rating-tags {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  padding: 0 16px;
}

.review-item {
  padding: 16px;
  border-bottom: 1px solid var(--van-border-color);
}

.review-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.review-user {
  flex: 1;
  margin-left: 12px;
}

.username {
  font-weight: 500;
}

.review-time {
  font-size: 12px;
  color: var(--van-text-color-2);
}

.review-content {
  line-height: 1.6;
  margin: 8px 0;
}

.review-reply {
  font-size: 14px;
  background-color: var(--van-background-color-light);
  padding: 8px 12px;
  border-radius: 4px;
  margin-top: 8px;
}

.confirm-item {
  margin-bottom: 12px;
}

.confirm-item .label {
  color: var(--van-text-color-2);
  margin-right: 8px;
}
</style> 